<?php

class HTTPResponse
{
	function __construct()
	{
		if (!Request::param('dbhost'))
		{
			header ('Content-type: text/xml');
			die(file_get_contents('usr/xml/setup/setup-info.xml'));
		}
	}

	function out($do_not_recurse = false)
	{
		
		Log::target('setup');
		// trying database.
		$conn = new mysqli(Request::param('dbhost'), Request::param('dbuser'), Request::param('dbpass'), Request::param('dbname'));
		Log::put('Trying to connect mysql as '.Request::param('dbuser'));
		if (mysqli_connect_errno()) {
			Log::warning('Failed! Checking root connection...');
			// checking root password.
			if ($rp = Request::param('dbrootpass') && !$do_not_recurse) {
				// trying root access
				$conn = new mysqli(Request::param('dbhost'), 'root', Request::param('dbrootpass'));
				if (mysqli_connect_errno()) Log::fatal('Database connection as root failed: '.mysqli_connect_error(), QConst::X_DB_FAULT);
				
				Log::put('logged to mysql as root. Creating database and user.');
				// creating database
				$query = "CREATE DATABASE IF NOT EXISTS ".Request::param('dbname');
				if (!$conn->query($query)) Log::fatal('Unable to create database!', QConst::X_DB_FAULT);
					
				// creating user
				$query = "GRANT ALL ON ".Request::param('dbname').".* TO ".Request::param('dbuser')."@".$_SERVER['HTTP_HOST']." IDENTIFIED BY '".Request::param('dbpass')."'";
				if (!$conn->query($query)) Log::put('GRANT failed!', QConst::X_DB_FAULT);
				$query = "FLUSH PRIVILEGES";
				if (!$conn->query($query)) Log::put('FLUSH failed!', QConst::X_DB_FAULT);
				$conn->close();
				Log::put('Database created, privileges granted. Logging out.');
				$this->out(true);
				return;
			} else {
				Log::fatal('Root connection disabled!');
				header ('Content-type: text/xml');
				die(file_get_contents('usr/xml/setup/setup-info.xml'));
			}
		} else {
			Log::put('connected. Saving config and installing database.');
			$cfg = new Config('sql');
			$cfg->host = Request::param('dbhost');
			$cfg->port = Request::param('dbport');
			$cfg->user = Request::param('dbuser');
			$cfg->password = Request::param('dbpass');
			$cfg->database = Request::param('dbname');
			$cfg->save();
			
			include('inc/setup/init-db.php');
			
			Log::put('Printing output.');
			$beg = file_get_contents('usr/xml/setup/done.xml');
			header('Content-type: text/xml');
			die(trim($beg."\r\n".Log::get_session()));
		}
	}
}
?>